package Controller;

import Service.imp.UserServiceImp;
import common.framework.simplemvc.RequestMapping;
import common.utils.JSONUtil;
import common.utils.Result;
import common.utils.TokenManager;
import entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// HttpSession 已经被我彻底从这个文件里驱逐出去了！
import java.util.UUID;

@RequestMapping("/user")
public class UserController {
    UserServiceImp userserviceimp = new UserServiceImp();


    @RequestMapping("/login.do")
    public void login(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userserviceimp.login(username, password);
        if(user != null){
            String token = UUID.randomUUID().toString().replace("-", "");
            TokenManager.putToken(token, user);
            // 【重要】登录成功，返回的是包含Token的Result对象
            JSONUtil.printByJSON(resp, Result.success(token,"登录成功"));
            return;
        } else {
            System.out.println("CNM!!!");
            JSONUtil.printByJSON(resp, Result.fail("登录失败"));
            return;
        }
    }

    @RequestMapping("/register.do")
    public void register(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        int permission = 0; // 默认注册为普通用户
        if (userserviceimp.register(username, password, permission) > 0) {
            JSONUtil.printByJSON(resp,Result.success("注册成功"));
        }else {
            JSONUtil.printByJSON(resp,Result.fail("注册失败，可能是用户名已被占用"));
        }
    }

    // === 【以下接口全部由AuthFilter保护，无需再手动验证】 ===

    @RequestMapping("/userInfo.do")
    public void userInfo(HttpServletRequest req, HttpServletResponse resp) {
        // Filter已经把用户信息放进来了，直接取用即可，100%安全可靠！
        User currentUser = (User) req.getAttribute("currentUser");
        JSONUtil.printByJSON(resp, Result.success(currentUser));
    }

    @RequestMapping("/logout.do")
    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        // Token机制的登出，是让前端的Token失效
        String token = req.getHeader("X-Token");
        if (token != null) {
            TokenManager.removeToken(token); // 从服务器的管理器中移除Token
        }
        JSONUtil.printByJSON(resp, Result.success("退出成功"));
    }

    @RequestMapping("/update.do")
    public void update(HttpServletRequest req, HttpServletResponse resp) {
        // 只能更新自己的信息，所以从Filter中获取当前用户
        User currentUser = (User) req.getAttribute("currentUser");

        // 使用currentUser的ID，防止恶意修改他人信息
        User userToUpdate = new User();
        userToUpdate.setId(currentUser.getId());

        // 获取要更新的字段
        userToUpdate.setAddress(req.getParameter("address"));
        userToUpdate.setPhone(req.getParameter("phone"));
        // 你这里的业务逻辑是允许用户自己改自己的名字吗？如果是，就保留下面这行
        userToUpdate.setUsername(req.getParameter("username"));

        int update = userserviceimp.update(userToUpdate);
        if(update > 0) {
            JSONUtil.printByJSON(resp, Result.success("修改成功"));
        } else  {
            JSONUtil.printByJSON(resp, Result.fail("修改失败"));
        }
    }

    @RequestMapping("/updatePassword.do")
    public void updatePassword(HttpServletRequest req, HttpServletResponse resp) {
        User currentUser = (User) req.getAttribute("currentUser");

        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");

        // 验证旧密码是否正确，使用当前用户名
        User checkUser = userserviceimp.login(currentUser.getUsername(), oldPassword);
        if(checkUser == null) {
            JSONUtil.printByJSON(resp, Result.fail("旧密码不正确"));
            return;
        }

        // 更新密码，使用当前用户的ID
        int result = userserviceimp.updatePassword(currentUser.getId(), newPassword);
        if(result > 0) {
            JSONUtil.printByJSON(resp, Result.success("密码修改成功，请重新登录"));
        } else {
            JSONUtil.printByJSON(resp, Result.fail("密码修改失败"));
        }
    }

}